package com.example.first.interceptors;

import okhttp3.Interceptor;
import okhttp3.Response;
import android.content.Context;
import android.content.Intent;
import androidx.appcompat.app.AppCompatActivity;

import com.example.first.activities.LoginActivity;
import com.example.first.utils.RetrofitClient;

import java.io.IOException;

public class UnauthorizedInterceptor implements Interceptor {

    private final Context context;

    public UnauthorizedInterceptor(Context context) {
        this.context = context;
    }

    @Override
    public Response intercept(Chain chain) throws IOException {
        Response response = chain.proceed(chain.request());

        if (response.code() == 401) {

            RetrofitClient.setToken(null);
            // 处理 401 响应码
            handleUnauthorized();
        }

        return response;
    }

    private void handleUnauthorized() {
        // 跳转到登录界面
        Intent intent = new Intent(context, LoginActivity.class);
        context.startActivity(intent);
        ((AppCompatActivity) context).finish();
    }
}
